﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Vin.Extension.Framework.Wechat.Pay.Service;
using Vin.Tool.AspNetCore.Singleton;

namespace Vin.Extension.Framework.Wechat.Pay.BackgroundServices;

public class TenpayCertificateRefreshingBackgroundService : BackgroundService
{
    private readonly ILogger<TenpayCertificateRefreshingBackgroundService> _logger;

    public TenpayCertificateRefreshingBackgroundService(ILogger<TenpayCertificateRefreshingBackgroundService> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                await VinApp.CreateScopeAsync(async provider =>
                {
                    var certificatesRefreshService =
                        provider.GetRequiredService<CertificatesRefreshV3BaseService>();
                    await certificatesRefreshService.Refresh();
                });
                // 每隔 1 天刷新一次
                await Task.Delay(TimeSpan.FromDays(1));
            }
            catch (global::System.Exception ex)
            {
                _logger.LogError(ex, "刷新微信商户平台证书遇到异常。");
                await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
            }
        }
    }
}